package com.ls.fw.search.lucene.util;

import java.io.StringReader;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;


/**
 * 高亮处理工具类
 * 
 * @author lisheng
 * @date 2014年12月24日 上午9:47:23
 * @version V1.0
 */
public class HighLightUtil {

	/**
	 * 高亮处理文字
	 * @param value 字符串
	 * @param field 字段
	 * @param query 查询条件
	 * @return
	 * @throws Exception
	 */
	public static String highlightFormat(String value, String field,   
            Query query) throws Exception {  
        QueryScorer scorer  = new QueryScorer(query,field);  
        SimpleHTMLFormatter hlightFormater = new SimpleHTMLFormatter("<span class=\"highlight\">", "</span>");  
        Highlighter hl = new Highlighter(hlightFormater,scorer);  
        hl.setTextFragmenter(new SimpleSpanFragmenter(scorer));   
        TokenStream stream  = AnalyzerUtils.getInstance().tokenStream(  
                 field, new StringReader(value));  
          
        String valueWithHighlight = hl.getBestFragment(stream, value);    
        return valueWithHighlight;  
    } 
}
